package cn.itrip.order.controller;

import cn.itrip.dto.Dto;
import cn.itrip.order.service.CommentService;
import cn.itrip.order.service.HotelService;
import cn.itrip.order.service.ImageService;
import cn.itrip.order.service.LabelDicService;
import cn.itrip.pojo.ItripComment;
import cn.itrip.pojo.ItripImage;
import cn.itrip.pojo.ItripUser;
import cn.itrip.utlis.*;
import cn.itrip.vo.ItripImageVO;
import cn.itrip.vo.ItripLabelDicVO;
import cn.itrip.vo.comment.ItripAddCommentVO;
import cn.itrip.vo.comment.ItripHotelDescVO;
import cn.itrip.vo.comment.ItripScoreCommentVO;
import cn.itrip.vo.comment.ItripSearchCommentVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by LENOVO on 2018/8/26.
 *
 * 酒店评论相关接口定义
 */
@Controller
@RequestMapping("/api/comment")
public class CommentController {

    @Resource
    private VerifyToken verifyToken;
    @Resource
    private CommentService commentService;
    @Resource
    private SystemConfig systemConfig;
    @Resource
    private ImageService imageService;
    @Resource
    private LabelDicService labelDicService;
    @Resource
    private HotelService hotelService;

    @ApiOperation(value = "新增评论接口", httpMethod = "POST",
            protocols = "HTTP",produces = "application/json",
            response = Dto.class,notes = "新增评论信息"+
            "<p style=‘color:red’>注意：若有评论图片，需要传图片路径</p>"+
            "<p>成功：success = ‘true’ | 失败：success = ‘false’ 并返回错误码，如下：</p>" +
            "<p>错误码：</p>"+
            "<p>100003 : 新增评论失败 </p>"+
            "<p>100004 : 不能提交空，请填写评论信息</p>"+
            "<p>100005 : 新增评论，订单ID不能为空</p>"+
            "<p>100000 : token失效，请重登录 </p>")
    @RequestMapping(value = "/add",method= RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public Dto<Object> addComment(@RequestBody ItripAddCommentVO itripAddCommentVO, HttpServletRequest request) {
        //无userId处理
        System.out.println(itripAddCommentVO.getItripImages()[0].getImgurl());
        String token = request.getHeader("token");
        ItripUser itripUser = verifyToken.verifyToken(token);
        //判断token
        if (itripUser == null ) {

            return DtoUtils.returnFail("token失效，请重新登陆!", "10003");

        }
        if ( itripAddCommentVO == null) {
            return DtoUtils.returnFail("参数错误！", "10005");
        }
        //判断订单id是否存在
        if (itripAddCommentVO.getOrderId() == null) {
            return DtoUtils.returnFail("订单id不能为空！", "10004");
        }
        //构建评论类
        ItripComment itripComment = new ItripComment();
        itripComment.setContent(itripAddCommentVO.getContent());
        itripComment.setHotelid(itripAddCommentVO.getHotelId());
        itripComment.setIshavingimg(itripAddCommentVO.getIsHavingImg());
        itripComment.setPositionscore(itripAddCommentVO.getPositionScore());
        itripComment.setFacilitiesscore(itripAddCommentVO.getFacilitiesScore());
        itripComment.setHygienescore(itripAddCommentVO.getHygieneScore());
        itripComment.setOrderid(itripAddCommentVO.getOrderId());
        itripComment.setServicescore(itripAddCommentVO.getServiceScore());
        itripComment.setProductid(itripAddCommentVO.getProductId());
        itripComment.setProducttype(itripAddCommentVO.getProductType());
        itripComment.setIsok(itripAddCommentVO.getIsOk());
        itripComment.setTripmode(Long.parseLong(itripAddCommentVO.getTripMode()));
        itripComment.setCreatedby(itripUser.getId());
        itripComment.setCreationdate(new Date(System.currentTimeMillis()));
        itripComment.setUserid(itripUser.getId());
        //判断是否有图片上传
        List<ItripImage> itripImageList = null;
        try {
            if (itripAddCommentVO.getIsHavingImg() == 1) {
                itripImageList = new ArrayList<ItripImage>();
                //loop input imgs array
                int i = 1;
                //取出回传的图片类 进行数据填充
                for (ItripImage itripImage : itripAddCommentVO.getItripImages()) {
                    itripImage.setPosition(i);
                    itripImage.setCreatedby(itripUser.getId());
                    itripImage.setCreationdate(itripComment.getCreationdate());
                    itripImage.setType("2");

                    itripImageList.add(itripImage);
                    i++;
                }
            }
            //将评论数据添加到数据库，以及相应的图片信息
            commentService.saveComment(itripComment, itripImageList);

        }catch (Exception e){
            e.printStackTrace();
            return DtoUtils.returnFail("保存失败！", "10007");

        }
        return DtoUtils.returnSuccess("保存评论成功！");

    }
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "图片上传接口", httpMethod = "POST",
            protocols = "HTTP",produces = "multipart/form-data",
            response = Dto.class, notes = "上传评论图片，最多支持4张图片同时上传，格式为：jpg、jpeg、png，大小不超过5M"+
            "<p style=‘color:red’>注意：input file 中的name不可重复 e:g : file1 、 file2 、 fileN</p>"+
            "<p>成功：success = ‘true’ | 失败：success = ‘false’ 并返回错误码，如下：</p>" +
            "<p>错误码：</p>"+
            "<p>100006 : 文件上传失败 </p>"+
            "<p>100007 : 上传的文件数不正确，必须是大于1小于等于4 </p>" +
            "<p>100008 : 请求的内容不是上传文件的类型 </p>" +
            "<p>100009 : 文件大小超限 </p>"
    )
    public Dto<Object> uploadPic(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {

        //返回数据定义
        Dto<Object> dto = new Dto<Object>();
        //保存上传图片的数组
        List<String> dataList = new ArrayList<String>();

        String path =request.getSession().getServletContext().getRealPath("statics" + File.separator + "images");
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //判斷文件數量
            int fileCount = 0;
            try{
                fileCount = multiRequest.getFileMap().size();
            }catch (Exception e) {
                // TODO: handle exception
                fileCount = 0;
                return DtoUtils.returnFail("文件大小超限","100009");
            }

            if(fileCount > 0 && fileCount <= 4 ){
                String tokenString  = multiRequest.getHeader("token");
                ItripUser itripUser = verifyToken.verifyToken(tokenString);
                if(null != itripUser){
                    //取得request中的所有文件名
                    Iterator<String> iter = multiRequest.getFileNames();
                    while(iter.hasNext()){

                        try{
                            //根據文件名稱獲取 得上传文件
                            MultipartFile file = multiRequest.getFile(iter.next());
                            if(file != null){
                                //取得当前上传文件的文件名称
                                String myFileName = file.getOriginalFilename();
                                //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                                if(myFileName.trim() !="" && (
                                        //判斷文件後綴名
                                          myFileName.toLowerCase().contains(".jpg")
                                                        || myFileName.toLowerCase().contains(".jpeg")
                                                        || myFileName.toLowerCase().contains(".png")
                                        )){
                                    //重命名上传后的文件名
                                    //命名规则：用户id+当前时间+随机数
                                    String suffixString = myFileName.substring(file.getOriginalFilename().indexOf("."));
                                    String fileName = itripUser.getId()+ "-" + System.currentTimeMillis() + "-" + ((int)(Math.random()*10000000)) + suffixString;
                                    //定义上传路径
                                    path = path + File.separator +fileName+"_200x200.jpg";
                                    File localFile = new File(path);
                                    if(!localFile.exists()){
                                        localFile.mkdirs();
                                    }
                                    //執行上傳操作
                                    System.out.println(fileName);
                                    file.transferTo(localFile);
                                    //上傳之後 拿到圖片存儲位置返回前 段  “/”符号固定写
                                    dataList.add(systemConfig.getVisitImgUrlString() + "/" +fileName);
                                }
                            }
                        }catch (Exception e) {
                            System.out.println("上傳錯誤！");
                            continue;
                        }
                    }
                    dto = DtoUtils.returnSuccess("文件上传成功",dataList);
                }else{
                    dto = DtoUtils.returnFail("文件上传失败","100006");
                }
            }else{
                dto = DtoUtils.returnFail("上传的文件数不正确，必须是大于1小于等于4","100007");
            }
        }else{
            dto = DtoUtils.returnFail("请求的内容不是上传文件的类型","100008");
        }
        return dto;
    }


    @ApiOperation(value = "据酒店id查询酒店平均分", httpMethod = "GET",
            protocols = "HTTP",produces = "application/json",
            response = Dto.class,notes = "总体评分、位置评分、设施评分、服务评分、卫生评分"+
            "<p>成功：success = ‘true’ | 失败：success = ‘false’ 并返回错误码，如下：</p>" +
            "<p>错误码：</p>"+
            "<p>100001 : 获取评分失败 </p>"+
            "<p>100002 : hotelId不能为空</p>")
    @RequestMapping(value = "/gethotelscore/{hotelId}",method=RequestMethod.GET,produces = "application/json")
    @ResponseBody
    public Dto<Object> getHotelScore(@ApiParam(required = true, name = "hotelId", value = "酒店ID")
                                     @PathVariable String hotelId) {
        ItripScoreCommentVO itripScoreCommentVO = null;
        try {
            itripScoreCommentVO = commentService.getScoreCommentVo(Long.parseLong(hotelId));
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtils.returnFail(e.getMessage(),"10010");
        }
        return DtoUtils.returnDataSuccess(itripScoreCommentVO);
    }


    @RequestMapping(value = "/delpic",produces="application/json",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "图片删除接口", httpMethod = "POST",
            protocols = "HTTP",produces = "application/json",
            response = Dto.class, notes = "删除传递图片名称"+
            "<p>成功：success = ‘true’ | 失败：success = ‘false’ 并返回错误码，如下：</p>" +
            "<p>错误码：</p>"+
            "<p>100010 : 文件不存在，删除失败 </p>"+
            "<p>100000 : token失效，请重登录 </p>")
    public Dto<Object> delPic(@RequestParam String imgName,HttpServletRequest request) throws IllegalStateException, IOException {
        //判断token是否有效
        String token = request.getHeader("token");
            ItripUser itripUser = verifyToken.verifyToken(token);
            if(itripUser == null){
                return DtoUtils.returnFail("token无效，请重新登陆！","100000");
            }
            if(imgName == null || imgName==""){
                return DtoUtils.returnFail("文件名不能为空！","10015");
            }


            File file = new File(systemConfig.getFileUploadPathString()+File.separator+imgName);
            if(file.exists()){
                file.delete();
                return DtoUtils.returnSuccess();
            }else {
                return DtoUtils.returnFail("文件不存在！","100010");
            }
    }

    @ApiOperation(value = "根据targetId查询评论照片(type=2)", httpMethod = "GET",
            protocols = "HTTP",produces = "application/json",
            response = Dto.class,notes = "总体评分、位置评分、设施评分、服务评分、卫生评分"+
            "<p>成功：success = ‘true’ | 失败：success = ‘false’ 并返回错误码，如下：</p>" +
            "<p>错误码：</p>"+
            "<p>100012 : 获取评论图片失败 </p>"+
            "<p>100013 : 评论id不能为空</p>")
    @RequestMapping(value = "/getimg/{targetId}",method=RequestMethod.GET,produces = "application/json")
    @ResponseBody
    public Dto<Object> getImgByTargetId(@ApiParam(required = true, name = "targetId", value = "评论ID")
                                        @PathVariable String targetId){

        List<ItripImageVO> list = null;
        try {
            list = imageService.selectImgByTargetId(Long.parseLong(targetId));
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtils.returnFail(e.getMessage(),"100015");
        }

        return DtoUtils.returnDataSuccess(list);
    }

    @ApiOperation(value = "根据酒店id查询各类评论数量", httpMethod = "GET",
            protocols = "HTTP",produces = "application/json",
            response = Dto.class,notes = "根据酒店id查询评论数量（全部评论、值得推荐、有待改善、有图片）"+
            "<p>成功：success = ‘true’ | 失败：success = ‘false’ 并返回错误码，如下：</p>" +
            "<p>错误码：</p>"+
            "<p>100014 : 获取酒店总评论数失败 </p>"+
            "<p>100015 : 获取酒店有图片评论数失败</p>"+
            "<p>100016 : 获取酒店有待改善评论数失败</p>"+
            "<p>100017 : 获取酒店值得推荐评论数失败</p>"+
            "<p>100018 : 参数hotelId为空</p>")
    @RequestMapping(value = "/getcount/{hotelId}",method=RequestMethod.GET,produces = "application/json")
    @ResponseBody
    public Dto<Object> getCommentCountByType(@ApiParam(required = true, name = "hotelId", value = "酒店ID")
                                                 @PathVariable String hotelId){
        Map<String,Integer> countMap = new HashMap<String,Integer>();
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("hotelId",hotelId);
        int count = 0;
        try {
           count = commentService.selectByHotel(param);

           countMap.put("allcomment",count);

           param.put("isOk",1);//0：有待改善 1：值得推荐
            count = commentService.selectByHotel(param);
            countMap.put("isok",count);

            param.put("isOk",0);//0：有待改善 1：值得推荐
            count = commentService.selectByHotel(param);
            countMap.put("improve",count);

            param.put("isHavingImg",1);//0:无图片 1:有图片
            param.put("isOk",null);//0：有待改善 1：值得推荐
            count = commentService.selectByHotel(param);
            countMap.put("havingimg",count);


        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtils.returnFail(e.getMessage(),"122222");
        }

        return DtoUtils.returnDataSuccess(countMap);
    }

    @ApiOperation(value = "查询出游类型列表", httpMethod = "GET",
            protocols = "HTTP",produces = "application/json",
            response = Dto.class,notes = "查询出游类型列表"+
            "<p>成功：success = ‘true’ | 失败：success = ‘false’ 并返回错误码，如下：</p>" +
            "<p>错误码：</p>"+
            "<p>100019 : 获取旅游类型列表错误 </p>")
    @RequestMapping(value = "/gettraveltype",method=RequestMethod.GET,produces = "application/json")
    @ResponseBody
    public Dto<Object> getTravelType(){
        Long parentId = 107L;

        List<ItripLabelDicVO> labelDicVOS = labelDicService.selectByVOList(parentId);

        return DtoUtils.returnSuccess("获取成功！",labelDicVOS);
    }


    @ApiOperation(value = "根据评论类型查询评论列表，并分页显示", httpMethod = "POST",
            protocols = "HTTP",produces = "application/json",
            response = Dto.class,notes = "根据评论类型查询评论列表，并分页显示"+
            "<p>参数数据e.g：</p>" +
            "<p>全部评论：{\"hotelId\":10,\"isHavingImg\":-1,\"isOk\":-1,\"pageSize\":5,\"pageNo\":1}</p>" +
            "<p>有图片：{\"hotelId\":10,\"isHavingImg\":1,\"isOk\":-1,\"pageSize\":5,\"pageNo\":1}</p>" +
            "<p>值得推荐：{\"hotelId\":10,\"isHavingImg\":-1,\"isOk\":1,\"pageSize\":5,\"pageNo\":1}</p>" +
            "<p>有待改善：{\"hotelId\":10,\"isHavingImg\":-1,\"isOk\":0,\"pageSize\":5,\"pageNo\":1}</p>" +
            "<p>成功：success = ‘true’ | 失败：success = ‘false’ 并返回错误码，如下：</p>" +
            "<p>错误码：</p>"+
            "<p>100020 : 获取评论列表错误 </p>")
    @RequestMapping(value = "/getcommentlist",method=RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public Dto<Object> getCommentList(@RequestBody ItripSearchCommentVO itripSearchCommentVO){

        if(itripSearchCommentVO.getHotelId() == null || itripSearchCommentVO.equals("")){
            return DtoUtils.returnFail("参数酒店id不能为空！","100124");
        }

        if(itripSearchCommentVO.getIsOk() < 0){
            itripSearchCommentVO.setIsOk(null);
        }
        if(itripSearchCommentVO.getIsHavingImg() < 0){
            itripSearchCommentVO.setIsHavingImg(null);
        }

        Map param = new HashMap();

        param.put("hotelId",itripSearchCommentVO.getHotelId());
        param.put("isHavingImg",itripSearchCommentVO.getIsHavingImg());
        param.put("isOk",itripSearchCommentVO.getIsOk());

        Page page = null;
        try {
            page = commentService.selectByPage(param,itripSearchCommentVO.getPageSize(),itripSearchCommentVO.getPageNo());
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtils.returnFail("查询失败！","1234513");
        }


        return DtoUtils.returnDataSuccess(page);
    }

    @ApiOperation(value = "获取酒店相关信息（酒店名称、酒店星级）", httpMethod = "GET",
            protocols = "HTTP",produces = "application/json",
            response = Dto.class,notes = "新增评论信息页面内获取酒店相关信息（酒店名称、酒店星级）"+
            "<p>成功：success = ‘true’ | 失败：success = ‘false’ 并返回错误码，如下：</p>" +
            "<p>错误码：</p>"+
            "<p>100021 : 获取酒店相关信息错误 </p>")
    @RequestMapping(value = "/gethoteldesc/{hotelId}",method=RequestMethod.GET,produces = "application/json")
    @ResponseBody
    public Dto<Object> getHotelDesc(@ApiParam(required = true, name = "hotelId", value = "酒店ID")
                                    @PathVariable String hotelId){
        ItripHotelDescVO itripHotelDescVO = null;
        try {
            itripHotelDescVO = hotelService.selectDescVOByHotelId(Long.parseLong(hotelId));
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtils.returnFail(e.getMessage(),"21351431");
        }

        return DtoUtils.returnDataSuccess(itripHotelDescVO);
    }

}
